from spConstants import *
from time import sleep, clock


########################################################################
class SmallProtocol_framer:
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        self.__buffer = bytearray()
        self.__header = {}
        self.__hsize  = 0x01        

    def __calcCRC(self, buffer):
        bcc = 0
        for i in buffer:
            bcc = bcc + i
        bcc = bcc % 256	
        return bcc

    def __CRC_Check(self, buffer):
        """
        """
        ret = False
        if(len(buffer)==1):
            if(buffer[0]==ACK or buffer[0]==NAK):
                ret = True
            
        elif(len(buffer)>1):
            bcc = self.__calcCRC(buffer[:len(buffer)-1])
            ret = bcc == buffer[len(buffer)-1]
        else:
            ret = False
        
        return ret
    
    def buildPacket(self, buffer, protocol=False):

        """
          Input:		buffer, protocol
          Output:		---
          Description:    Sends data to display, adding protocol:
                          DC1/DC2 | length | data..... | bcc
                          <DC1> = 17(dec.) = 0x11 <DC2> = 18(dec.) = 0x12 
                          length = count of user data (without <DC1/DC2>, without checksum bcc)
                          bcc = 1 byte = sum of all bytes incl. <DC1/DC2> and len, modulo 256
                          sends array, using uart_send(), lenght = data amount to be send
                          protocol = False (Command/Data to the display)
                          protocol = True (protocoll commands to the display)
          """

        lenbuf = len(buffer)			#length without DC and bcc	
        if(protocol):                           # protocol commands to display
            buffer.insert(0, 0x12)		#send DC2				
        else:					#Command/Data to the display
            buffer.insert(0, 0x11)		#send DC1

        buffer.insert(1, lenbuf)                #send data length

        bcc = self.__calcCRC(buffer)
        buffer.append(bcc)
        return buffer    
          
             
    def processIncomingPacket(self, data, payload):
        buffer = list(bytearray(data))
        if(not payload):  # only ACK or NAK
            if(len(buffer)==1):
                return (buffer[0]), bytearray()
            else:
                #clear buffer?????
                return NAK, bytearray()
        else:                       
            if self.__CRC_Check(buffer[1:]):
                
                start  = 3
                end = buffer[2]+3
                             
                buffer = buffer[start:end]
                return ACK, buffer                     
            else: 
                print "check frame failed"
                print "buffer: " + " ".join([hex(x) for x in buffer])
                return NAK, bytearray()
             